package cn.com.haopy.yue.ai.wx.web;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.com.haopy.yue.ai.core.utils.IpUtil;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.db.service.hos.HOSUserService;
import cn.com.haopy.yue.ai.wx.dto.WxLoginInfo;
import cn.com.haopy.yue.ai.wx.service.WxHOSUserService;
import cn.com.haopy.yue.ai.wx.web.base.BaseWxController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录
 */
@RestController
@RequestMapping("/haopyYueAi/login")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "登录")
public class WxLoginController extends BaseWxController {

    @Autowired
    WxHOSUserService wxHOSUserService;

    @Autowired
    HOSUserService hosUserService;

    @Autowired
    WxMaService wxMaService;

    @PostMapping("/login")
    @ApiOperation(value = "手机登录(调试)")
    public Object login(@RequestBody WxLoginInfo wxLoginInfo) {


        if (!StringUtils.hasText(wxLoginInfo.getMobile())) {
            return ResponseUtil.badArgument();
        }

        return wxHOSUserService.loginMobile(wxLoginInfo.getMobile());
    }



    @PostMapping("/wxLogin")
    @ApiOperation(value = "微信登录")
    public Object wxLogin(@RequestBody WxLoginInfo wxLoginInfo) {

        if (wxLoginInfo.getCode() == null || wxLoginInfo.getUserInfo() == null) {
            return ResponseUtil.badArgument();
        }

        String sessionKey = null;
        String openId = null;
        String unionId = null;

        try {
            WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(wxLoginInfo.getCode());
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            unionId = result.getUnionid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            return ResponseUtil.failMsg("微信登录失败");
        }

        return wxHOSUserService.wxLogin(wxLoginInfo.getUserInfo(), sessionKey, openId, unionId, IpUtil.getIpAddr(request));
    }


}